<template>
  <h3>shallowReactive, shallowRef 以及 isReactive, isRef, triggerRef 函数的演示</h3>

  <hr>
  <div>个人信息 (<b>shallowReactive</b> 演示):</div>
  <div class="single">姓名: {{person.name}}</div>
  <div class="single">年龄: {{person.age}}</div>
  <div class="single">薪水: {{person.job.job1.salary}}K</div>
  <div>所有信息: {{person}}</div>

  <button @click="person.name += '~'">修改姓名</button>
  <button @click="person.age++">修改年龄</button>
  <button @click="person.job.job1.salary++">涨薪</button>

  <hr>
  <div style="margin-bottom: 8px;"><b>shallowRef</b> 演示</div>
  <button @click="count++">计数加一</button>
  <div>当前计数 ( 基本数据类型 ): {{count}}</div>
  <br>
  <button @click="book.price++">书本价格加一</button>
  <button @click="replaceBook">替换成新书</button>
  <button @click="triggerBook">手动应用修改数据 ( <b>triggerRef</b> )</button>
  <div>书本全部信息: {{book}}</div>
  <hr>
  <p>
    注意:<br>
    1. shallowReactive 只处理对象最外层属性的响应式,即浅层响应式.<br>
    2. shallowRef 只处理基本数据类型的响应式,不处理对象中属性的响应式,但整体替换对象时也可以做到响应式.<br>
    3. 何时使用这两个函数?<br>
    &nbsp;&nbsp;&nbsp;&nbsp;1). 如果对象数据结构比较深,但只有外层属性发生变化,则可以用 shallowReactive 来做成响应式.这比reactive性能要好些.<br>
    &nbsp;&nbsp;&nbsp;&nbsp;2). 如果对象数据在修改时不会直接改其属性,而是用新的对象来整体替换,则可以用 shallowRef.<br>
  </p>
</template>

<script>
import { shallowRef, shallowReactive, isReactive, isRef, triggerRef } from 'vue'

export default {
  setup() {
    let person = shallowReactive({
      name: '张三',
      age: 33,
      job: {
        job1: {
          salary: 22
        }
      },
    })

    let count = shallowRef(0)

    let book = shallowRef({
      name: 'World war II',
      price: 99
    })

    console.log('person is reactive? ', isReactive(person), ', persion is ref?', isRef(person))
    console.log('count is reactive? ', isReactive(count), ', count is ref?', isRef(count))
    console.log('count.value is reactive? ', isReactive(count.value), ', count.value is ref?', isRef(count.value))
    console.log('book is reactive? ', isReactive(book), ', book is ref?', isRef(book))
    console.log('book.value is reactive? ', isReactive(book.value), ', book.value is ref?', isRef(book.value))

    let index = 1

    function replaceBook(){
      book.value = {
        name: 'New Book ' + index,
        price: 10 + index
      }
      index++
    }

    function triggerBook(){
      triggerRef(book)
    }

    //expose 
    return {
      person,
      count,
      book,
      replaceBook,
      triggerBook
    }
  },
}
</script>

<style scoped>

h3 {
  text-align: center;
}

button {
  margin-left: 5px;
}

.single {
  margin-top: 5px;
}

</style>